// 可见性事实管理器 - 仅用于控制题目可见性
import { getUserInfo } from '@/util/request.js'

/**
 * 可见性事实管理器
 * 仅支持 userinfo 数据源，用于 visibleWhen 条件判断
 */
class FactsManager {
    constructor() {
        this.factSources = new Map();
    }

    /**
     * 注册事实数据源
     * @param {string} sourceId - 数据源标识
     * @param {Function} getter - 获取数据的函数
     */
    registerSource(sourceId, getter) {
        this.factSources.set(sourceId, getter);
    }

    /**
     * 异步初始化用户信息数据源
     */
    async initializeUserInfoSource() {
        try {
            const userInfo = await getUserInfo();
            this.registerSource('userinfo', () => ({
                gender: userInfo.gender,
                age: userInfo.age,
                education_level: userInfo.education_level,
            }));
            console.log('User info source initialized:', userInfo);
        } catch (e) {
            console.warn('Failed to initialize user info source:', e);
            this.registerSource('userinfo', () => ({}));
        }
    }

    /**
     * 获取所有患者事实数据
     * @returns {Object} 合并后的患者事实数据
     */
    getAllFacts() {
        const allFacts = {};

        // 按优先级合并各个数据源
        for (const [sourceId, getter] of this.factSources) {
            try {
                const sourceFacts = getter();
                Object.assign(allFacts, sourceFacts);
            } catch (e) {
                console.warn(`Failed to get facts from source ${sourceId}:`, e);
            }
        }

        return allFacts;
    }

    /**
     * 获取指定事实值
     * @param {string} factId - 事实标识
     * @returns {*} 事实值
     */
    getFact(factId) {
        const allFacts = this.getAllFacts();
        return allFacts[factId];
    }
}

// 创建全局实例
const factsManager = new FactsManager();
// 兼容新命名

/**
 * 初始化可见性事实管理器
 */
export const initializeVisibilityFacts = async () => {
    try {
        await factsManager.initializeUserInfoSource();
        console.log('Visibility facts manager initialized successfully');
    } catch (e) {
        console.error('Failed to initialize visibility facts manager:', e);
    }
}

/**
 * 获取事实值
 * @param {string} factId - 事实标识
 * @returns {*} 事实值
 */
export const getFact = (factId) => {
    return factsManager.getFact(factId);
}

export { factsManager };
